import {
  Component,
  OnInit,
  OnChanges,
  Output,
  EventEmitter,
  Input,
  SimpleChanges,
  OnDestroy
} from '@angular/core';
import { Router } from '@angular/router';


@Component({
  selector: 'app-side-menu',
  templateUrl: './side-menu.component.html',
  styleUrls: ['./side-menu.component.scss'],
})
export class SideMenuComponent implements OnInit, OnChanges, OnDestroy {
  menus = [];
  constructor(
    private router: Router,
  ) { }
  isCollapsed = true;
  // 该组件是否展示
  // @Input() showsidemenu = false;
  @Input() closeMenuItem = null; // 引发了ngonchange事件。。。。。
  // 当前选择的item
  currentSelect = '';
  // 二级菜单是否为展开状态
  visible = false;
  title = '';                          // 被激活模块主键
  subscripitions = [];
  @Output() sideBarEventEmitter = new EventEmitter<any>();
  @Input() data = null;

  ngOnInit() {
    postal.channel('TWOLEVEL_PANEL_CHANNEL').subscribe('cctv-twopanel', res => {
      this.currentSelect = res.title;
      // this.open(res);
    });
  }

  muneClick(item) {
    // 如果为雨水动态和污水动态，则不执行关闭操作，主界面一般总要存在一个是处于激活状态的!
    if ((item.title === '雨水动态' && this.currentSelect === '雨水动态') || (item.title === '污水动态' && this.currentSelect === '污水动态')) {
      return;
    }
    // this.router.navigate([`/business/${jtem.value}`]);
    // 点击模块为激活模块则关闭
    if (item.title === this.currentSelect) {
      this.close();
    }// 点击模块不为激活模块打开
    else {
      this.currentSelect = item.title;
      this.open(item);
    }
  }


  // 二级页面展开功能
  open(item): void {
    // 当前显示，但点击模块不为当前模块
    if (this.visible === true && this.title !== item.title) {
      this.title = item.title;
    } else {// 当前不显示
      this.title = item.title;
      this.visible = true;
    }
    // 往外传输信息
    this.sideBarEventEmitter.emit({ data: item, visible: true });
  }
  // 关闭时传输信息
  close(): void {
    // 重置当前选择模块与二级页面显示状态
    this.title = '';
    this.visible = false;
    this.currentSelect = '';
    // 往外传输信息
    this.sideBarEventEmitter.emit({ data: '', visible: false });
  }
  ngOnChanges(changes: SimpleChanges): void {
    if (changes.closeMenuItem) {
      this.close();
      this.currentSelect = '';
    }
    if (changes.data && changes.data.currentValue) {
      // 判断data里是不是存在select === true的对象，存在的话，设置其状态为激活状态！
      this.data = changes.data.currentValue;
      this.data.forEach(element => {
        if (element.selected) {
          this.currentSelect = element.title;
          this.open(element);
        }
      });
    }
  }

  ngOnDestroy() {
    this.subscripitions.forEach(element => {
      element.unsubscribe();
    });
  }

}
